/*
 * ButtonBase.cpp
 *
 *  Created on: 09/12/2011
 *      Author: Tales
 */
#include "ButtonBase.hpp"
namespace yep
{
ButtonBase::ButtonBase(const string & text) :
		_text(text)
{
	_status = RELEASED;
}

void ButtonBase::onDraw(SDL_Surface *screen)
{
	style->drawButton(screen, _status, _text, isFocused(),
			getAbsolutePosition(), getAbsoluteArea(), getTextColor(),
			getBackgroundColor());
}

bool ButtonBase::onEvent(SDL_Event & event)
{
	switch (event.type)
	{
	case SDL_MOUSEBUTTONUP:
		if (event.button.button
				& (SDL_BUTTON_LEFT | SDL_BUTTON_RIGHT | SDL_BUTTON_MIDDLE))
		{
			_status = RELEASED;
			Rect absoluteArea_(getAbsolutePosition().x, getAbsolutePosition().y,
					getAbsoluteArea().getW(), getAbsoluteArea().getH());
			if (event.button.x >= absoluteArea_.x()
					&& event.button.x <= absoluteArea_.getX2()
					&& event.button.y >= absoluteArea_.y()
					&& event.button.y <= absoluteArea_.getY2())
			{
				onAction();
			}
		}
		break;
	case SDL_KEYDOWN:
		if (event.key.keysym.sym == SDLK_SPACE && isFocused())
		{
			_status = PRESSED;
			return true;
		}
		break;
	case SDL_KEYUP:
		if (event.key.keysym.sym == SDLK_SPACE)
		{
			_status = RELEASED;
			if (isFocused())
				onAction();
		}
		break;
	default:
		break;
	}
	return false;
}

bool ButtonBase::onClickDown(SDL_MouseButtonEvent & buttonEvent)
{
	_status = PRESSED;
	return false;
}

void ButtonBase::onAction()
{
	_action(*this);
	return;
}

void ButtonBase::autoResize()
{
	Uint16 w, h;
	style->buttonArea(_text, w, h);
	Rect newArea(getRect());
	if (newArea.w() < w)
		newArea.setW(w);

	if (newArea.h() < h)
		newArea.setH(h);

	setRect(newArea);
}
void ButtonBase::status(ButtonStatus value)
{
	_status = value;
}

ButtonStatus ButtonBase::status() const
{
	return _status;
}

void ButtonBase::action(ActionBase & value)
{
	_action = value;
}

const ActionBase & ButtonBase::action() const
{
	return _action;
}

string ButtonBase::text() const
{
	return _text;
}
}
